package com.adayo.memoryfree.activity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.text.format.Formatter;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.adayo.memoryfree.R;
import com.adayo.memoryfree.adapter.RublishMemoryAdapter;
import com.adayo.memoryfree.base.BaseSwipeBackActivity;
import com.adayo.memoryfree.bean.CacheListItem;
import com.adayo.memoryfree.bean.StorageSize;
import com.adayo.memoryfree.quickreturn.enums.QuickReturnType;
import com.adayo.memoryfree.quickreturn.listeners.QuickReturnListViewOnScrollListener;
import com.adayo.memoryfree.service.CleanerService;
import com.adayo.memoryfree.utils.JStorageKit;
import com.adayo.memoryfree.utils.JToastKit;
import com.adayo.memoryfree.widgets.TitleView;
import com.adayo.memoryfree.widgets.textcounter.CounterView;
import com.adayo.memoryfree.widgets.textcounter.formatters.DecimalFormatter;
import com.nhaarman.listviewanimations.itemmanipulation.swipedismiss.OnDismissCallback;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

public class RubbishCleanActivity extends BaseSwipeBackActivity implements OnDismissCallback, CleanerService.OnActionListener{

	@ViewInject(R.id.tv_title)
	private TitleView titleView;
	private CleanerService mCleanerService;
	private boolean mAlreadyScanned = false;

	@ViewInject(R.id.listview)
	ListView mListView;
	@ViewInject(R.id.empty)
	TextView mEmptyView;
	@ViewInject(R.id.header)
	RelativeLayout header;
	@ViewInject(R.id.textCounter)
	CounterView textCounter;
	@ViewInject(R.id.sufix)
	TextView sufix;

	@ViewInject(R.id.progressBar)
	View mProgressBar;
	@ViewInject(R.id.progressBarText)
	TextView mProgressBarText;

	RublishMemoryAdapter rublishMemoryAdapter;

	List<CacheListItem> mCacheListItem = new ArrayList<>();

	@ViewInject(R.id.bottom_lin)
	LinearLayout bottom_lin;

	private ServiceConnection mServiceConnection = new ServiceConnection() {
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mCleanerService = ((CleanerService.CleanerServiceBinder) service).getService();
			mCleanerService.setOnActionListener(RubbishCleanActivity.this);

			if (!mCleanerService.isScanning() && !mAlreadyScanned) {
				mCleanerService.scanCache();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mCleanerService.setOnActionListener(null);
			mCleanerService = null;
		}
	};

	@Override
	protected int getLayoutId() {
		return R.layout.activity_rubbish_clean;
	}

	@Override
	protected void initParams(Bundle savedInstanceState) {
		titleView.setResource(R.drawable.selector_return_btn,
				R.string.app_rublish_clean);
		titleView.setLeftClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});

		int footerHeight = getResources().getDimensionPixelSize(R.dimen.footer_height);
		mListView.setEmptyView(mEmptyView);
		rublishMemoryAdapter = new RublishMemoryAdapter(context, mCacheListItem);
		mListView.setAdapter(rublishMemoryAdapter);
		mListView.setOnItemClickListener(rublishMemoryAdapter);
		mListView.setOnScrollListener(new QuickReturnListViewOnScrollListener(QuickReturnType.FOOTER, null, 0, bottom_lin, footerHeight));
		bindService(new Intent(context, CleanerService.class),
				mServiceConnection, Context.BIND_AUTO_CREATE);
	}

	@Override
	protected String[] initPermissions() {
		return new String[0];
	}

	@Event(value = {R.id.clear_button})
	private void onViewClick(View v) {
		if (mCleanerService != null && !mCleanerService.isScanning() &&
				!mCleanerService.isCleaning() && mCleanerService.getCacheSize() > 0) {
			mCleanerService.cleanCache();
		}
	}

	@Override
	public void onDismiss(@NonNull ViewGroup listView, @NonNull int[] reverseSortedPositions) {

	}

	@Override
	public void onScanStarted(Context context) {
		mProgressBarText.setText(R.string.scanning);
		showProgressBar(true);
	}

	@Override
	public void onScanProgressUpdated(Context context, int current, int max) {
		mProgressBarText.setText(getString(R.string.scanning_m_of_n, current, max));
	}

	@Override
	public void onScanCompleted(Context context, List<CacheListItem> apps) {
		showProgressBar(false);
		mCacheListItem.clear();
		mCacheListItem.addAll(apps);
		rublishMemoryAdapter.notifyDataSetChanged();
		header.setVisibility(View.GONE);
		if (apps.size() > 0) {
			header.setVisibility(View.VISIBLE);
			bottom_lin.setVisibility(View.VISIBLE);

			long medMemory = mCleanerService != null ? mCleanerService.getCacheSize() : 0;

			StorageSize mStorageSize = JStorageKit.convertStorageSize(medMemory);
			textCounter.setAutoFormat(false);
			textCounter.setFormatter(new DecimalFormatter());
			textCounter.setAutoStart(false);
			textCounter.setStartValue(0f);
			textCounter.setEndValue(mStorageSize.value);
			textCounter.setIncrement(5f); // the amount the number increments at each time interval
			textCounter.setTimeInterval(50); // the time interval (ms) at which the text changes
			sufix.setText(mStorageSize.suffix);
			textCounter.start();
		} else {
			header.setVisibility(View.GONE);
			bottom_lin.setVisibility(View.GONE);
		}

		if (!mAlreadyScanned) {
			mAlreadyScanned = true;
		}
	}

	@Override
	public void onCleanStarted(Context context) {
		if (isProgressBarVisible()) {
			showProgressBar(false);
		}

		if (!RubbishCleanActivity.this.isFinishing()) {
			showWaitDialog("扫描中", true, null);
		}
	}

	private boolean isProgressBarVisible() {
		return mProgressBar.getVisibility() == View.VISIBLE;
	}

	private void showProgressBar(boolean show) {
		if (show) {
			mProgressBar.setVisibility(View.VISIBLE);
		} else {
			mProgressBar.startAnimation(AnimationUtils.loadAnimation(
					context, android.R.anim.fade_out));
			mProgressBar.setVisibility(View.GONE);
		}
	}

	@Override
	public void onCleanCompleted(Context context, long cacheSize) {
		dismissDialog();
//		JToastKit.getInstance().showMessage(getString(R.string.cleaned, Formatter.formatShortFileSize(
//				context, cacheSize)));
		header.setVisibility(View.GONE);
		bottom_lin.setVisibility(View.GONE);
		mCacheListItem.clear();
		rublishMemoryAdapter.notifyDataSetChanged();
	}

	public void onDestroy() {
		unbindService(mServiceConnection);
		super.onDestroy();
	}
}
